package com.myxml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import java.util.List;

public class XPathQuery {
    public static void main(String[] args) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read("book.xml");
            
            // 1. 查询所有编程类书籍
            List<Node> progBooks = document.selectNodes("//book[@category='编程']");
            System.out.println("\n编程类书籍:");
            progBooks.forEach(node -> {
                Element book = (Element) node;
                System.out.println(" - " + book.elementText("title"));
            });
            
            // 2. 查询特定ID的书籍价格
            Node priceNode = document.selectSingleNode("//book[@id='b102']/price");
            System.out.println("\n算法导论价格: " + priceNode.getText());
            
            // 3. 查询所有中文书籍
            List<Node> chineseBooks = document.selectNodes("//book[title/@lang='zh']");
            System.out.println("\n中文书籍:");
            chineseBooks.forEach(node -> {
                Element book = (Element) node;
                System.out.println(" - " + book.elementText("title"));
            });
            
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}